package com.sanmubird.mywebframework.indicator.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.sanmubird.mywebframework.indicator.domain.executor.IndicatorExecutorProvider;
import com.sanmubird.mywebframework.indicator.domain.executor.JavaExecutor;
import com.sanmubird.mywebframework.indicator.domain.executor.SqlExecutor;
import com.sanmubird.mywebframework.indicator.domain.model.IndicatorExecutor;
import com.sanmubird.mywebframework.indicator.domain.model.IndicatorType;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


/**
 * @author sam
 */
@Configuration
public class IndicatorExecutorConfig {


    @Bean
    public IndicatorExecutorProvider indicatorExecutorProvider(ApplicationContext beanProvider) {
        Map<IndicatorType, IndicatorExecutor> indicatorTypeExecutorMap = new HashMap<>(16);
        // 注入 Java 类型执行器
        indicatorTypeExecutorMap.put(IndicatorType.JAVA, new JavaExecutor(beanProvider));

        Map<String, DataSource> beans = beanProvider.getBeansOfType(DataSource.class);
        Map<String, JdbcTemplate> jdbcTemplateMap = new HashMap<>(8);
        beans.forEach((k, v) -> {
            if (v instanceof DynamicRoutingDataSource) {
                DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) v;
                Map<String, DataSource> sources = dynamicRoutingDataSource.getCurrentDataSources();
                sources.forEach((key, value) -> jdbcTemplateMap.put(key, new JdbcTemplate(value)));
            } else {
                jdbcTemplateMap.put(k, new JdbcTemplate(v));
            }
        });
        // 注入 SQL 类型执行器
        indicatorTypeExecutorMap.put(IndicatorType.SQL, new SqlExecutor(jdbcTemplateMap));
        return new IndicatorExecutorProvider(indicatorTypeExecutorMap);
    }
}
